package com.myblog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myblog.common.ResultInfoFactory;
import com.myblog.model.po.SysRole;
import com.myblog.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/role")
@Slf4j
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;


    private static final String HTML_PREFIX="system/role/";

    @GetMapping(value = {"/",""})
    public String role(){
        return HTML_PREFIX+"role-list";
    }

    @PreAuthorize("hasAuthority('sys:role:list')")
    @ResponseBody
    @PostMapping("/page")
    public ResultInfoFactory page(Page<SysRole> page, SysRole sysRole){
        IPage<SysRole> sysRoleIPage = sysRoleService.selectPage(page, sysRole);
        return ResultInfoFactory.success(sysRoleIPage);
    }

    @PreAuthorize("hasAnyAuthority('sys:role:add','sys:role:edit')")
    @GetMapping(value = {"/form","/form/{id}"})
    public String form(@PathVariable(required = false)Long id, Model model){
        SysRole sysRole = sysRoleService.findById(id);
        model.addAttribute("role",sysRole);
        return HTML_PREFIX+"role-form";
    }

    @PreAuthorize("hasAnyAuthority('sys:role:add','sys:role:edit')")
    @RequestMapping(value = {"/saveOrUpdate"},method = {RequestMethod.POST,RequestMethod.PUT})
    public String saveOrUpdate(SysRole sysRole){
        //log.info(sysRole.toString());
        sysRoleService.saveOrUpdate(sysRole);
        return "redirect:/role";
    }

    @PreAuthorize("hasAuthority('sys:role:delete')")
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResultInfoFactory deleteById(@PathVariable("id") Long id){
        sysRoleService.deleteById(id);
        return ResultInfoFactory.success();
    }



}
